#include "circle.h"
#include "Fitting/gauss/CircleFitter.h"
#include <Eigen/Core>
#include <Eigen/Sparse>
#include <Eigen/Dense>

namespace  ELEMENT {
    Circle::Circle():Element()
    {
        type = ElementType::Circle;
    }

    bool Circle::fit(const std::vector<Point> &points)
    {
        Fitting::FittingBase* fb = new Gauss::CircleFitter();
        auto err = fb->Fitting(points, &circle);
        delete fb;

        if(err<0) {
            return false;
        }
        int pnum=100;
        vertices.resize(pnum);
        index.resize(pnum+1);
        auto first = (points[0]-circle.center).cross(circle.orient).normalized();
        first*=circle.r;
        qDebug()<< first.x()<<first.y()<<first.z();
        qDebug()<< (points[0]-circle.center).cross(circle.orient).normalized().x()<<(points[0]-circle.center).cross(circle.orient).normalized().y()<<(points[0]-circle.center).cross(circle.orient).normalized().z();
        qDebug()<< (points[0]-circle.center).cross(circle.orient).x()<<(points[0]-circle.center).cross(circle.orient).y()<<(points[0]-circle.center).cross(circle.orient).z();
        auto ax = Eigen::AngleAxisd(M_PI*2/pnum, circle.orient).toRotationMatrix();
        vertices[0] = circle.center+first;
        index[0]=0;
        for(int i=1;i<pnum;++i) {
            //index[i*2]=i;
            //index[i*2+1]=i+1;
            index[i]=i;
            vertices[i]=ax*(vertices[i-1]-circle.center)+circle.center;
        }
        //vertices[pnum]=vertices[0];
        index[pnum]=0;

        return true;
    }

    void Circle::Draw(QOpenGLShaderProgram &shader)
    {
        shader.bind();
        shader.setUniformValue("userColor",QVector4D(0.1f, 0.1f, 0.0f, 1.0f));
        QOpenGLVertexArrayObject::Binder bind(&VAO);
        glLineWidth(2);
        glDrawElements(GL_LINE_STRIP, index.size(), GL_UNSIGNED_INT, 0);

        //shader.setUniformValue("userColor",QVector4D(0.1f, 0.5f, 0.0f, 1.0f));
        //glDrawElements(GL_LINE_STRIP, index.size(), GL_UNSIGNED_INT, 0);
    }

    QString Circle::Info()
    {
        QString info("类型：圆\n半径：%1\n圆心：%2 %3 %4\n法向：%5 %6 %7");
        return info.arg(circle.r)
                .arg(circle.center.x()).arg(circle.center.y()).arg(circle.center.z())
                .arg(circle.orient.x()).arg(circle.orient.y()).arg(circle.orient.z());
    }

}
